package com.accp.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;

import com.accp.dao.UsersDao;
import com.accp.pojo.Users;
/**
 * 用户数据访问对象实现类
 * @author Administrator
 *
 */
public class UsersDaoImpl extends BaseDaoImpl implements UsersDao {
	/**
	 * 用户登录
	 */
	@SuppressWarnings("unchecked")
	public List<Users> login(Users user) {
		List<Users> list = new ArrayList<Users>();
		try{
			String hql = "from Users where userName=:userName and userPwd=:userPwd"; //Users必须和类名相同，区分大小写
			list = getSession().createQuery(hql)
								.setString("userName", user.getUserName())
								.setString("userPwd", user.getUserPwd())
								.list();
		}catch(HibernateException e){
			e.printStackTrace();
		}
			return list;
	}
	/**
	 * 修改用户信息
	 */
	@Override
	public boolean update(Users user) {
		boolean flag = false;
		try{
			getSession().update(user);
			flag = true;
		}catch(HibernateException e){
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * 查询所有用户信息
	 */
	@SuppressWarnings("unchecked")
	@Override

	public List<Users> findExceptMe(String userName) {
		List<Users> list = new ArrayList<Users>();
		try{
			String hql = "from Users where userName !=:userName"; //查询除了当前用户的所有用户
			list = getSession().createQuery(hql).setString("userName", userName).list();
		}catch(HibernateException e){
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 添加用户
	 */
	@Override
	public boolean add(Users user) {
		boolean flag = false;
		try{
			getSession().save(user);
			flag = true;
		}catch(HibernateException e){
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * 删除用户
	 */
	@Override
	public boolean deleteUser(Users user) {
		boolean flag = false;
		try{
			getSession().delete(user);
			flag = true;
		}catch(HibernateException e){
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * 通过ID查找用户
	 */
	@Override
	public Users findByUserName(String userName) {
		Users user = (Users) getSession().get(Users.class,new String(userName));
		return user;
	}
	/**
	 * 重载父类的该方法
	 * 分页查看，获取总记录数。
	 */
	
	public int totalPage(String className,String userName) {
		String hql = "select count(*) from "+ className + " where userName !=:userName";
		Query query = this.getSession().createQuery(hql).setString("userName", userName);
		int total = Integer.parseInt(query.list().get(0).toString());
		return total;
	}
	/**
	 * 分页查询，查询首页
	 */
	@SuppressWarnings("unchecked")
	public List<Users> selectByPage(String className, int pageNo, int pageSize,
			String userName) {
		Query query = this.getSession().createQuery("from "+ className + " where userName !=:userName")
						.setString("userName", userName);
	
		query.setFirstResult((pageNo - 1) * pageSize);//每页显示的第一条记录
		query.setMaxResults(pageSize);//每页显示的记录数
		return query.list();
	}

}
